<template>
    <div class="cate-container mt50 mb60">
        <van-nav-bar fixed left-arrow @click-left="$router.go(-1)" title="商品列表"></van-nav-bar>
        <!-- 商品列表 -->
        <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
            <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                <van-card lazy-load @click="goGoods(item.id)" v-for="item in goodsList" :key="item.id" :price="item.price"
                    :title="item.goodsname" :thumb="$baseUrl + item.img" />
            </van-list>
        </van-pull-refresh>
        <van-empty v-if="goodsList.length === 0" description="暂无商品数据"></van-empty>
    </div>
</template>

<script>
export default {
    data() {
        return {
            page: 1,
            size: 5,
            goodsList: [],
            total: 0,
            // 列表数组是否加载完毕, 默认值不能给true, 否则load事件将不执行
            finished: false,
            loading: false,
            // 下拉刷新loading
            isLoading: false
        }
    },
    mounted() {
        // 请求分类商品数据
        this.getGoodsList();
    },
    methods: {
        // 下拉刷新
        onRefresh() {
            // 开启下拉刷新loading
            this.isLoading = true;
            // 重新请求数据
            this.getGoodsList();
        },
        // 加载下一页数据
        onLoad() {

            if (this.goodsList.length < this.total) {
                //开启loading效果
                this.loading = true;
                // 页码+1
                this.page += 1;
                // 根据最新页码请求数据
                this.getGoodsList();
            }

        },
        goGoods(id) {
            this.$router.push({ name: "goods", query: { id } });
        },
        getGoodsList() {
            const { cateid } = this.$route.query;
            if (!cateid) {
                this.$toast('参数错误');
                return this.$router.push('/index');
            }
            const params = { page: this.page, size: this.size, cateid }
            this.$axios.get('/getgoodslist', { params }).then(res => {
                if (res.code === 200) {
                    const { goodsData = [], total = 0 } = res.list;
                    // 更新商品列表数组
                    this.goodsList = [...this.goodsList, ...goodsData];
                    // 更新数据总条数
                    this.total = total;
                    setTimeout(() => {
                        // 关闭上拉加载更多loading加载效果
                        this.loading = false;
                        // 关闭下拉更新loading
                        this.isLoading = false;
                    }, 1000);
                    if (this.goodsList.length === this.total) {
                        // 数据加载完毕
                        this.finished = true;
                    }
                }
            });
        }
    }
}
</script>

<style></style>